<template>
  <div id="TabContainer">
    <ShopHeader/>
    <!-- 导航栏 -->
    <div class="tabs">
      <div class="tab-item">
        <router-link to="/shop/meal" replace>订餐</router-link>
      </div>
      <div class="tab-item">
        <router-link to="/shop/rating" replace>评论</router-link>
      </div>
      <div class="tab-item">
        <router-link to="/shop/info" replace>商家</router-link>
      </div>
    </div>
    <!-- 路由占位符 -->
    <router-view></router-view>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import {SHOP_DATAS, ADD_CART} from '../../store/mutations_type'
import ShopHeader from '../../components/ShopHeader/ShopHeader'
export default {
  components: {
    ShopHeader
  },
  async mounted() {
    // 刷新后需要读取数据
    // 1. 读取sessionStorage中的shopDatas
    let shopDatas = JSON.parse(sessionStorage.getItem('shopDatas'))

    if(shopDatas) {
      // 2. 将shopData里的数据存储到Vuex中
      this.$store.commit(SHOP_DATAS, shopDatas)
      // 3. 刷新后存在shopDatas和shopcart失联,需要在vuex中把shopcart更新
      let shopCart = shopDatas.goods.reduce((pre, good) => {
        pre.push(...good.foods.filter(food => food.count ))
        return pre
      }, [])
      // 4. 修改vuex中shopcart数据
      this.$store.commit(ADD_CART, shopCart)
    } else {
      // 分发action,发请求获取数据
      this.$store.dispatch('getShopDatasAction')
    }

    // 页面刷新前将shopdatas存入sessionStorage中
    window.addEventListener('unload', () => {
      sessionStorage.setItem('shopDatas', JSON.stringify(this.shopdatas))
    })
  },
  beforeDestroy() {
    // 如果页面没刷新,只是后退至首页,也需要在sessionStorage中存入shopdatas
    sessionStorage.setItem('shopDatas', JSON.stringify(this.shopdatas))  
  },
  computed: {
    ...mapState({
      shopdatas: state => state.shop.shopdatas
    })
  }
}
</script>

<style lang="stylus">
@import '../../common/stylus/mixins.styl'
#TabContainer
  .tabs
    display flex
    bottom-border-1px(#eee)
    .tab-item
      flex 1
      height 40px
      line-height 40px    
      text-align center
      font-size 16px
      a
        display block
        position relative
        &.router-link-active
          color $green
          &:after
            content ''
            position absolute
            height 5px
            width 40px
            left 50%
            bottom 0
            background $green
            transform scaleY(0.5)
            margin-left -20px
</style>